var isSet = false;

var picture_width;
var picture_height;
var crop_max_width;
var crop_max_height;

var scopePic = 1;

var jcrop_api,boundx,boundy;

$(function () {
    isSet = check();
    $preview = $('#preview-pane'),
    $pcnt =  $(".preview-container"),
    $pimg =  $(".preview-container img"),
    xsize = $pcnt.width(),
    ysize = $pcnt.height();
    crop_max_height = $(".srcImg").height();
    crop_max_width = $(".srcImg").width();

    // $(".imgload").click(function(){
    //     $('#fileupload').click();
    // });


    $(document).on("click",".success",function(){
        $.ajax({
            type:'post',
            url:'../jcrop/demos/crop.php',
            data:{
                x:Math.floor($("#x").val()) * scopePic,
                y:Math.floor($("#y").val()) * scopePic,
                w:Math.floor($("#w").val()) * scopePic,
                h:Math.floor($("#h").val()) * scopePic,
                imgSrc:$("#imgSrc").val()
            },
            dataType:'json',
            async:false,
            success:function(data){
                reset(1);
                if(isSet){
                    $(".img").css({
                        "background-image":'url(' + data.url + ')'
                    })
                }else{
                    // 兼容性
                    $(".img img").attr("src",data.url).show();
                }
            }
        });
    })

    $(document).on("click",".default",function(){
        reset(0)
    })

    fileup();
});

function reset(status){
    $(".imgModel").hide();
    $(".srcImg img,#preview").attr("src","");
    if(status==1){
        // 点击确定按钮
        $(".img img").hide();
    }else{
        // 点击取消按钮
        $(".img img").show()
    }
    $("#fileupload").val('');
    jcrop_api.destroy();
    // $(".img").attr("style","");
    $(".img").css({
        "background-image":'none'
    })

    $("#cropbox").remove();
    $(".srcImg").append('<img src="" id="cropbox"/>')
}

function picture(input) {
    if(isSet){
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (event) {
                setImg(event.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    // imageCrop();
}

function imageCrop(){
    $(".cutpic").unbind('click').hide();
    $("#cropbox").Jcrop({
        aspectRatio: xsize / ysize,
        boxWidth: crop_max_width,
        boxHeight: crop_max_height,
        onChange: updateCoords,
        onSelect: updateCoords
    }
    ,function(){
    // Use the API to get the real image size
        var bounds = this.getBounds();
        boundx = bounds[0];
        boundy = bounds[1];
        // Store the API in the jcrop_api variable
        jcrop_api = this;

        jcrop_api.setSelect(getRandom());

        // Move the preview into the jcrop container for css positioning
        // $preview.appendTo(jcrop_api.ui.holder);
    }
    );
}

function updateCoords(c){
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
    $('#x2').val(c.x2);
    $('#y2').val(c.y2);

    if (parseInt(c.w) > 0)
    {
    var rx = xsize / c.w;
    var ry = ysize / c.h;

    $('.preview-container img').css({
        width: Math.round(rx * boundx) + 'px',
        height: Math.round(ry * boundy) + 'px',
        marginLeft: '-' + Math.round(rx * c.x) + 'px',
        marginTop: '-' + Math.round(ry * c.y) + 'px'
    });
    }
};

function checkCoords()
{
    if (parseInt($('#w').val())) return true;
    alert('请选择需要裁剪的图片');
    return false;
};

// Use the API to find cropping dimensions
// Then generate a random selection
// This function is used by setSelect and animateTo buttons
// Mainly for demonstration purposes
function getRandom() {
    var dim = jcrop_api.getBounds();
    return [
    Math.round(Math.random() * dim[0]),
    Math.round(Math.random() * dim[1]),
    Math.round(Math.random() * dim[0]),
    Math.round(Math.random() * dim[1])
    ];
};

function fileup(){
    // Change this to the location of your server-side upload handler:
    var url = '/server/php/';
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        autoUpload: true,
        // limit 2M max fileSize
        maxFileSize: 2 * Math.pow(10,6),
        maxNumberOfFiles:1,
        done: function (e, data) {
            var Srcurl = '';
            $.each(data.result.files, function (index, file) {
                // debugger;
               Srcurl = file.url;
            });
            if(!isSet){
                setImgForIE(Srcurl);
            }
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        }
        // ,add: function (e, data) {            
        //     $("#up_btn").off('click').on('click', function () {
        //         data.submit();
        //     });
        // }
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
}